﻿#include "Camera.h"
#include <spdlog/spdlog.h>

engine::render::Camera::Camera(glm::vec2 viewportSize, glm::vec2 position, std::optional<engine::utils::Rect> mimit_bounds):
	m_viewportSize(viewportSize), m_position(position), m_limit_bounds(mimit_bounds)
{
	spdlog::info("Camera 初始化成功 位置: ({}, {})", m_position.x, m_position.y);
}

void engine::render::Camera::update(float deltaTime)
{

}

void engine::render::Camera::move(const glm::vec2& delta)
{
	m_position += delta;
	clampPosition();
}

glm::vec2 engine::render::Camera::worldToScreen(const glm::vec2& worldPos) const
{
	return worldPos - m_position;
}

glm::vec2 engine::render::Camera::worldToScreenwithParallax(const glm::vec2& worldPos, glm::vec2& scroll_factor) const
{
	return worldPos - m_position * scroll_factor;
}

glm::vec2 engine::render::Camera::screenToWorld(const glm::vec2& screemPos) const
{
	return screemPos + m_position;
}

void engine::render::Camera::setPosition(const glm::vec2& position)
{
	m_position = position;
	clampPosition();
}

void engine::render::Camera::setLimitBounds(const std::optional<engine::utils::Rect>& bounds)
{
	m_limit_bounds = bounds;
	clampPosition();
}

const glm::vec2& engine::render::Camera::getPosition() const
{
	return m_position;
}

const glm::vec2& engine::render::Camera::getViewportSize() const
{
	return m_viewportSize;
}

std::optional<engine::utils::Rect> engine::render::Camera::getLimitBounds() const
{
	return m_limit_bounds;
}

void engine::render::Camera::clampPosition()
{
	if (m_limit_bounds.has_value() && m_limit_bounds->size.x > 0 && m_limit_bounds->size.y > 0)
	{
		//计算相机位置的最大值
		glm::vec2 minPosition = m_limit_bounds->position;
		glm::vec2 maxPosition = m_limit_bounds->position + m_limit_bounds->size - m_viewportSize;
		//限制相机位置在边界内
		maxPosition.x = std::max(minPosition.x, maxPosition.x);
		maxPosition.y = std::max(minPosition.y, maxPosition.y);
		m_position = glm::clamp(m_position, minPosition, maxPosition);
	}
}